﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace TestSystem.DataManipulation.Helpers
{
    public static class CSVHelper
    {
        private static readonly List<Char> CSVDelimeters = new List<Char> { ',', ' ', ';' };
        private static Char? Delimeter;

        public static Boolean ValidateFileFormat (string filename)
        {
            var reader = new StreamReader(filename);
            var list = new List<string>();

            for (var i = 0; i < 10 && !reader.EndOfStream; i++)
                list.Add( reader.ReadLine());

            if (list.Count == 0) return false;
            var resultlist = new List<int>();
            foreach (var delimeter in CSVDelimeters)
            {
                
                resultlist.AddRange(
                    list.Select(elem => elem.Split(delimeter).Count()).Where(currentResult => currentResult > 2));
                if (resultlist.Count != list.Count) continue;
                if(!ValidateDelimeter(resultlist)) continue;
                
                resultlist.Clear();
                Delimeter = delimeter;

                break;
            }
            reader.Dispose();
            return Delimeter != null;
        }

        private static Boolean ValidateDelimeter(IList<int> resultlist)
        {
            
            for (var index = 1; index < resultlist.Count; index++)
           
                if (resultlist[index] != resultlist[index - 1]) return false;
              
           return true;
        }
        
    }
}
